#include <iostream>
#include <unistd.h>


using namespace std;

#include "threadbase.h"
#include "childthread.h"
#include "ThreadSafeQueue.h"

void* producer(void* arg) {
    ThreadSafeQueue<int>* queue = static_cast<ThreadSafeQueue<int>*>(arg);
    for(int i=0; i<5; ++i) {
        queue->push(i);
        std::cout << "Produced: " << i << std::endl;
        usleep(500000); // 0.5秒
    }
    return NULL;
}

void* consumer(void* arg) {
    ThreadSafeQueue<int>* queue = static_cast<ThreadSafeQueue<int>*>(arg);
    int value;
    while(true) {
        if(queue->timed_wait_and_pop(value, 1000)) { // 1秒超时
            std::cout << "Consumed: " << value << std::endl;
        } else {
            std::cout << "Timeout, retrying..." << std::endl;
        }
    }
    return NULL;
}

int main()
{
    cout << "Hello World!" << endl;

//    childThread t2;
//    t2.start(NULL, "t2");


//    while(1)
//    {
//        sleep(5);
//        t2.stop();
//        sleep(1);
//        if(t2.is_stop())
//        {
//            break;
//        }
//    }

    ThreadSafeQueue<int> queue;

    pthread_t prod, cons;
    pthread_create(&prod, NULL, producer, &queue);
    pthread_create(&cons, NULL, consumer, &queue);

    pthread_join(prod, NULL);
    pthread_join(cons, NULL);

    return 0;
}
